package com.javaAdmin.config;

import com.javaAdmin.util.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 全局返回封装
 *
 * @author Administrator
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    /**
     * supports方法:
     * 判断是否要执行beforeBodyWrite方法,true为执行,false不执行.
     * 通过该方法可以选择哪些类或那些方法的response要进行处理, 其他的不进行处理
     *
     * @param returnType    方法返回的类型
     * @param converterType 参数类型装换
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //System.out.println(Result.class);                            class com.javaAdmin.util.Result
        //System.out.println(returnType.getMethod().getReturnType());  class com.javaAdmin.model.Student
        //判断返回来源不相等的都当报错处理
        if (Result.class == returnType.getMethod().getReturnType()) {
            System.out.println("检测到自定义返回值，不走通用返回");
            return false;
        }
        return true;
    }

    /**
     * beforeBodyWrite方法: 对response方法进行具体操作处理
     *
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request               请求数据
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        System.out.println("响应拦截成功");

        return Result.success(body);
    }
}
